package com.bizihang.security.core.validate.code.generator.impl;

import com.bizihang.security.core.properties.ImageCodeProperties;
import com.bizihang.security.core.validate.code.image.ImageCode;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.image.BufferedImage;
import java.util.Properties;

/**
 * @author 毕子航 951755883@qq.com
 * @date 2018/08/18
 */
public class KaptcheImageCodeGenerator extends AbstractCodeGenerator {
	@Override
	public ImageCode generate(ServletWebRequest request) {
		ImageCodeProperties image = getSecurityProperties().getCode().getImage();
		int width = ServletRequestUtils.getIntParameter(request.getRequest(), "width", image.getWidth());
		int height = ServletRequestUtils.getIntParameter(request.getRequest(), "height", image.getHeight());
		DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
		Properties properties = new Properties();
		properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, String.valueOf(width));
		properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, String.valueOf(image.getLength()));
		properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, String.valueOf(height));
		defaultKaptcha.setConfig(new Config(properties));
		String text = defaultKaptcha.createText();
		BufferedImage bufferedImage = defaultKaptcha.createImage(text);
		int expireIn = getSecurityProperties().getCode().getImage().getExpireIn();
		return new ImageCode(bufferedImage, text, expireIn);
	}
}
